package com.abeir.bilibili.cmmand;

import com.abeir.bilibili.utils.Sundry;

import java.nio.file.Path;

public final class CommanderManager {

    private final Commander commander;

    private String ffmpeg;
    private String input;
    private String output;
    private String temporary;
    private String[] videoSuffixes;
    private String[] audioSuffixes;

    public CommanderManager(String applicationName){
        this.commander = createCommander(applicationName);
    }

    public String getFfmpeg() {
        return ffmpeg;
    }

    public String getInput(){
        return input;
    }

    public String getOutput(){
        return output;
    }

    public String getTemporary(){
        if(temporary == null || temporary.isEmpty()){
            temporary = Path.of(output, ".temp").toString();
        }
        return temporary;
    }

    public String[] getVideoSuffixes(){
        return videoSuffixes;
    }

    public String[] getAudioSuffixes(){
        return audioSuffixes;
    }

    public boolean parse(String[] args) throws Exception {
        return commander.parse(args);
    }

    public Commander createCommander(String applicationName) {
        Commander cmd = new CliCommander();
        cmd.setApplicationName(applicationName);
        cmd.setCallback(this::callback);
        registerCommands(cmd);
        return cmd;
    }

    private void registerCommands(Commander cmd){
        cmd.registerCommand("f", "ffmpeg", true, "ffmpeg executable program full path");
        cmd.registerCommand("i", "input", true, "root directory as input");
        cmd.registerCommand("o", "output", true, "as the directory for generating the final file");
        cmd.registerCommand("t", "temp", true, "as a directory for generating intermediate temporary files, if not set, a temporary directory will be created in the output directory");
        cmd.registerCommand("vs", "video-suffix", true, "suffixes of the video file");
        cmd.registerCommand("as", "audio-suffix", true, "suffixes of the audio file");
    }

    private void callback(Commander.Options options) throws OptionException {
        if(!options.hasOption("ffmpeg")){
            throw new OptionException("missing option: ffmpeg");
        }
        if(!options.hasOption("input")){
            throw new OptionException("missing option: input");
        }
        if(!options.hasOption("output")){
            throw new OptionException("missing option: output");
        }
        ffmpeg = Sundry.safePath(options.getValue("ffmpeg"));
        input = Sundry.safePath(options.getValue("input"));
        output = Sundry.safePath(options.getValue("output"));
        temporary = Sundry.safePath(options.getValue("temp"));
        videoSuffixes = options.getValues("video-suffix");
        audioSuffixes = options.getValues("audio-suffix");
    }

}
